package com.example.service;

import com.example.model.Question;
import com.example.repository.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class QuestionService {
    
    @Autowired
    private QuestionRepository questionRepository;
    
    @Autowired
    private OpenAiService openAiService;
    
    public Question createQuestion(String questionText, String answer) {
        Question question = new Question();
        question.setQuestion(questionText);
        question.setAnswer(answer);
        question.setCreateTime(LocalDateTime.now());
        question.setDifficulty(1);
        question.setLearned(false);
        question.setCollected(false);
        
        List<String> keywords = openAiService.analyzeTopicKeywords(questionText);
        question.setKeywords(String.join(",", keywords));
        
        return questionRepository.save(question);
    }
    
    public Question regenerateAnswer(Long id) {
        Question question = questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Question not found"));
            
        String newAnswer = openAiService.getAnswer(question.getQuestion());
        question.setAnswer(newAnswer);
        
        return questionRepository.save(question);
    }
    
    public List<Question> generateLearningList(String topic) {
        List<String> keywords = openAiService.analyzeTopicKeywords(topic);
        
        List<Question> results = new ArrayList<>();
        for (String keyword : keywords) {
            results.addAll(questionRepository.findByKeywords(keyword));
        }
        
        return results.stream().distinct().collect(Collectors.toList());
    }
    
    public void toggleCollect(Long id) {
        Question question = questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Question not found"));
        question.setCollected(!question.isCollected());
        questionRepository.save(question);
    }
    
    public void toggleLearned(Long id) {
        Question question = findById(id);
        question.setLearned(!question.isLearned());
        questionRepository.save(question);
        System.out.println("Question " + id + " learned status toggled to: " + question.isLearned());
    }
    
    public List<Question> getAllQuestions() {
        return questionRepository.findAllByOrderByCreateTimeDesc();
    }
    
    public List<Question> getCollectedQuestions() {
        return questionRepository.findByIsCollectedTrue();
    }
    
    public List<Question> getLearnedQuestions() {
        List<Question> learnedQuestions = questionRepository.findByIsLearnedTrue();
        System.out.println("Found " + learnedQuestions.size() + " learned questions");
        return learnedQuestions;
    }

    public List<Question> searchQuestions(String keyword) {
        return questionRepository.findByQuestionContainingOrAnswerContaining(keyword, keyword);
    }

    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalQuestions", questionRepository.count());
        stats.put("learnedCount", questionRepository.countByIsLearnedTrue());
        stats.put("collectedCount", questionRepository.countByIsCollectedTrue());
        
        Double avgDifficulty = questionRepository.getAverageDifficulty();
        stats.put("averageDifficulty", avgDifficulty != null ? avgDifficulty : 0.0);
        
        return stats;
    }

    public void updateDifficulty(Long id, int difficulty) {
        Question question = questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Question not found"));
        question.setDifficulty(difficulty);
        questionRepository.save(question);
    }

    public List<String> getAllTopics() {
        return questionRepository.findAllKeywords().stream()
            .flatMap(keywords -> Arrays.stream(keywords.split(",")))
            .distinct()
            .collect(Collectors.toList());
    }

    public Question findById(Long id) {
        return questionRepository.findById(id)
            .orElseThrow(() -> new RuntimeException("Question not found"));
    }

    public List<Question> getQuestionsByDateRange(LocalDateTime start, LocalDateTime end) {
        return questionRepository.findByCreateTimeBetweenOrderByCreateTimeDesc(start, end);
    }

    public List<Question> generateQuestionsForTopic(String topic, int count) {
        List<Question> questions = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            String questionPrompt = String.format("生成一个关于%s的面试问题", topic);
            String question = openAiService.getAnswer(questionPrompt);
            String answer = openAiService.getAnswer(question);
            
            Question q = new Question();
            q.setQuestion(question);
            q.setAnswer(answer);
            q.setCreateTime(LocalDateTime.now());
            q.setDifficulty(1);
            q.setLearned(false);
            q.setCollected(false);
            q.setKeywords(topic);
            
            questions.add(q);
        }
        return questions;
    }

    public SseEmitter streamAnswer(Long id) {
        Question question = findById(id);
        return openAiService.streamAnswer(question.getQuestion());
    }
    
    public SseEmitter streamNewAnswer(String question) {
        return openAiService.streamAnswer(question);
    }

    public Question updateCollectStatus(Long id, boolean isCollected) {
        Question question = findById(id);
        if (question == null) {
            throw new RuntimeException("问题不存在");
        }
        question.setCollected(isCollected);
        return questionRepository.save(question);
    }

    public void deleteQuestion(Long id) {
        Question question = findById(id);
        if (question == null) {
            throw new RuntimeException("问题不存在");
        }
        questionRepository.delete(question);
    }
} 